/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool ancestor(TreeNode* root, TreeNode* p, TreeNode* q, TreeNode*& result)
    {
        if (root == nullptr)
        {
            return false;
        }

        int left1 = ancestor(root->left, p, q, result);
        int right1 = ancestor(root->right, p, q, result);

        if (left1 && right1)
        {
            result = root;
            return true;
        }

        if ((left1 || right1) && (root == p || root == q))
        {
            result = root;
            return true;
        }

        if (left1 || right1)
        {
            return true;
        }

        if (root == p || root == q)
        {
            return true;
        }

        return false;
    }

    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        TreeNode* result = nullptr;
        ancestor(root, p, q, result);
        return result;
    }
};